package org.laobai.shop.protal.controller;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.dubbo.config.annotation.DubboReference;
import org.laobai.shop.goods.entity.Category;
import org.laobai.shop.goods.entity.Sku;
import org.laobai.shop.goods.entity.Spec;
import org.laobai.shop.goods.entity.Spu;
import org.laobai.shop.goods.service.CategoryService;
import org.laobai.shop.goods.service.SkuService;
import org.laobai.shop.goods.service.SpecService;
import org.laobai.shop.goods.service.SpuService;
import org.laobai.shop.goods.vo.SkuVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("home")
public class HomeController {
	@DubboReference
	private SpuService spuService;
	
	@DubboReference
	private CategoryService categoryService;
	
	@DubboReference
	private SkuService skuService;
	
	@DubboReference
	private SpecService specService;
	
	@RequestMapping("/")
	public String home(Model model){
		List<Category> tree = categoryService.getTreeByPid(0);
		model.addAttribute("tree",tree);
		return "home";
	}
	
	@RequestMapping("toDetails")
	public String toDetails(Integer categoryId,Model model){
		List<Spu> list = spuService.getListByCategoryId(categoryId);
		model.addAttribute("spus",list);
		return "search";
	}
	
	@RequestMapping("details")
	public String details(Integer spuId,Model model){
		// spu
		Spu spu = spuService.getById(spuId);
		// sku
		List<Sku> skus = skuService.getBySpuId(spuId);
		
		/* 
		List<Integer> skuIds = new ArrayList<>();
		skus.forEach(item->{
			skuIds.add(item.getId());
		});*/
		
		// 获取skuId
		List<Integer> skuIds = skus.stream().map(Sku::getId).collect(Collectors.toList());
		
		// 规格&规格属性
		List<Spec> specs = specService.getBySkuId(skuIds);
		
		model.addAttribute("spu",spu);
		model.addAttribute("skus",skus);
		model.addAttribute("specs",specs);
		
		return "introduction";
	}
	
	@RequestMapping("getSku")
	@ResponseBody
	public Sku getSku(@RequestBody List<SkuVO> vos){
		return skuService.getSku(vos);
	}
}
